import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ModalDirective} from "ngx-bootstrap";
import {adSystemApiUrl, tuikeSystemUrl, AliyunOssOutputUrl} from "../../../config/api";
import {HttpService} from "../../lib/service/http.service";
import {Headers, RequestOptions} from "@angular/http";
import {LoginService} from "../../lib/service/tuike-login.service";

@Component({
  selector: 'app-daily-task',
  templateUrl: './dailytask.component.html',
  styleUrls: ['./dailytask.component.scss'],
  providers: [LoginService]
})
export class DailytaskComponent implements OnInit {
  _startDate=null;
  _endDate=null;
  start_date="";
  end_date="";
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  searchData = '';
  status = '3';
  _task_times="";
  task_times="";
  type: string;
  message: string;
  isShow = true;
  totalItems: number;
  currentPage: number = 1;
  itemsPerPage: number = 20;
  _isSpinning = false;

  counts = {
    'count_0':0,
    'count_2':0,
    'count_1':0,
    'count_3':0
  };

  editItem;

  pageSize = 20;

  taskList = [];

  reject_result = '';
  integral = '';
  other_intergral = '';
  activeIntergral;

  dailyList = [];
  dailyTotal = 0;
  editSrc = '';

  @ViewChild('rejectModal') public rejectModal: ModalDirective;
  @ViewChild('passModal') public passModal: ModalDirective;
  @ViewChild('resetPsdModal') public resetPsdModal: ModalDirective;

  constructor(private httpService: HttpService, private el: ElementRef,private loginService: LoginService) {
  }

  ngOnInit() {
    this.getDailyTaskList(1);
  }

  //重置
  reset() {
    this.start_date="";
    this.end_date="";
    this._startDate=null;
    this._endDate=null;
    this._task_times="";
    this.task_times="";
    this.getDailyTaskList(1);
  }

  search1(){
    this.start_date=this._startDate?this.dateFtt('yyyy-MM-dd',this._startDate):"";
    this.end_date=this._endDate?this.dateFtt('yyyy-MM-dd',this._endDate):"";
    this.task_times=this._task_times;
    this.search();
  }

  //搜索
  search() {
    this.getDailyTaskList(1);
  }

  checkLength(e) {
    if (e.length > 30) {
      this.reject_result = e.substring(0, 29);
      this.el.nativeElement.querySelector('.reject_result').value = this.reject_result;
    }

  }

  _startValueChange = () => {
    if (this._startDate > this._endDate) {
      this._endDate = null;
    }
  };

  _endValueChange = () => {
    if (this._startDate > this._endDate) {
      this._startDate = null;
    }
  };

  _disabledStartDate = (startValue) => {
    if (!startValue || !this._endDate) {
      return false;
    }
    return startValue.getTime() >= this._endDate.getTime();
  };

  _disabledEndDate = (endValue) => {
    if (!endValue || !this._startDate) {
      return false;
    }
    return endValue.getTime() <= this._startDate.getTime();
  };
  dateFtt(fmt,date)
  { //author: meizz
    var o = {
      "M+" : date.getMonth()+1,                 //月份
      "d+" : date.getDate(),                    //日
      "h+" : date.getHours(),                   //小时
      "m+" : date.getMinutes(),                 //分
      "s+" : date.getSeconds(),                 //秒
      "q+" : Math.floor((date.getMonth()+3)/3), //季度
      "S"  : date.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
      fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
      if(new RegExp("("+ k +")").test(fmt))
    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
  }
  //获取每日任务列表
  getDailyTaskList(page) {
    this._isSpinning = true;
    let url = `${tuikeSystemUrl}/api/v1/admin/member_daliy_task/task_list?page=${page}&pageSize=${this.itemsPerPage}&stage=${this.status}`;
    if (this.start_date) {
      url+="&start_date="+this.start_date;
    }
    if(this.end_date){
      url+="&end_date="+this.end_date+" 23:59:59";
    }

    if (this.task_times) {
      url+="&task_times="+this.task_times;
    }
    console.log(this.start_date);
    console.log(url);
    this.httpService.httpGetAuth(url).subscribe(res => {
      if (res.code === 200) {
        this.dailyList = res.data.task_list.data;
        this.counts = res.data.tage;
        this.dailyList.map((e, i) => {
          e['upload_pic'] = JSON.parse(e['upload_pic']);
        });
        this.dailyTotal = res.data.task_list.total;
        this._isSpinning = false;
      }
    })
  }

  //通过任务
  passTask(data) {
    const url = `${tuikeSystemUrl}/api/v1/admin/member_daliy_task/pass`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify(data);
    return this.httpService.httpPostAuth(url, body, options).map(rs => rs);
  }

  //未通过任务
  unPassTask(data) {
    const url = `${tuikeSystemUrl}/api/v1/admin/member_daliy_task/un_pass`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify(data);
    return this.httpService.httpPostAuth(url, body, options).map(rs => rs);
  }

  showPreview(e) {
    let task = this.el.nativeElement.querySelector('.big-pic-wrap');
    let box = this.el.nativeElement.querySelector('.mask-box');
    box.style.display = 'block';
    // task.style.display = "block";
    task.style.top = "50%";
    this.editSrc = e.srcElement.currentSrc;
  }

  closeMask() {
    this.el.nativeElement.querySelector('.mask-box').style.display = 'none';
    this.el.nativeElement.querySelector('.big-pic-wrap').style.top = '2000px';
  }

  showRejectModal(item) {
    this.editItem = item;
    this.rejectModal.show();
  }

  showPassModal(item) {
    this.editItem = item;
    this.passModal.show();
  }

  addRejectFormSubmit() {
    if (this.reject_result == '') {
      this.type = 'error';
      this.message = '请输入拒绝理由';
      this.isShow = true;
    } else {
      let data = {
        task_id: this.editItem.id,
        err_code_des: this.reject_result
      };
      this.unPassTask(data).subscribe(res => {
          if (res.code === 200 && res.data === true) {
            this.rejectModal.hide();
            this.type = 'success';
            this.message = '任务不通过';
            this.isShow = true;
            this.reject_result = '';
            this.getDailyTaskList(this.currentPage);
          }
        }
      )
    }
  }

  addPassFormSubmit() {
    if (this.other_intergral && (this.other_intergral.indexOf('-') == -1) || this.integral) {
    } else if (this.other_intergral && !/^\+?[1-9][0-9]*$/.test(this.other_intergral) || this.other_intergral == '0') {
      this.type = 'error';
      this.message = '积分有误';
      this.isShow = true;
      return;
    } else {
      this.type = 'error';
      this.message = '积分有误';
      this.isShow = true;
      return;
    }
    let data = {};
    data['task_id'] = this.editItem['id'];
    data['member_id'] = this.editItem['member_id'];
    data['member_uid'] = this.editItem['member_uid'];
    data['openId'] = this.editItem['openId'];
    let point = 0;
    if (this.other_intergral) {
      point = parseInt(this.other_intergral);
    } else {
      point = parseInt(this.integral);
    }
    data['point'] = point;
    this.passTask(data).subscribe(res => {
      if (res.code === 200 && res.data === true) {
        this.passModal.hide();
        this.type = 'success';
        this.message = '审核通过';
        this.isShow = true;
        this.integral = null;
        this.other_intergral = '';
        this.activeIntergral = 5;
        this.getDailyTaskList(this.currentPage);
      }
    });
  }

  pageChanged(event: any): void {
    window.scrollTo(0, 0);
    this.getDailyTaskList(event.page);
  }


  clearIntergral() {
    this.activeIntergral = 5;
    this.integral = '';
  }

}
